package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.dao.OrdersDao;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.*;
import org.apache.tomcat.jni.Local;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersDao, Orders> implements OrdersService {

    // 注入购物车数据
    @Autowired
    private ShoppingCartService shoppingCartService;
    // 注入用户数据
    @Autowired
    private UserService userService;
    // 注入地址信息
    @Autowired
    private AddressBookService addressBookService;
    // 注入订单明细
    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 用户下单
     * @param orders
     * @return
     */
    @Transactional
    public void submit(Orders orders) {
        // 获得当前用户id
        Long userId = BaseContext.getCurrentId();
        // 查询当前用户的购物车,根据ID来进行查询
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(queryWrapper);
        // 判断购物车是否为空,如果为空,则抛出一个自定义异常
        if (shoppingCarts == null || shoppingCarts.size() == 0){
            throw new CustomException("购物车为空,不能下单");
        }
        // 查询用户数据
        User user = userService.getById(userId);
        // 查询地址信息
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        if (addressBook == null){
            throw new CustomException("用户地址信息有误,请查证后再试");
        }

        long orderId = IdWorker.getId(); // 订单号
        // 用这个对象计算总金额,原子操作,保证线程安全
        AtomicInteger amount = new AtomicInteger(0);
        // 遍历购物车数据,计算出来,还需要将订单明细数据封装出来
        List<OrderDetail> orderDetails = shoppingCarts.stream().map((item)->{
            OrderDetail orderDetail = new OrderDetail();  // 创建一个订单明细实体
            orderDetail.setOrderId(orderId);  // 设置订单号
            orderDetail.setNumber(item.getNumber());  // 菜品(套餐)数量
            orderDetail.setDishFlavor(item.getDishFlavor()); // 口味
            orderDetail.setDishId(item.getDishId());  // 菜品id
            orderDetail.setSetmealId(item.getSetmealId());  // 套餐id
            orderDetail.setName(item.getName()); // 菜品(套餐)名称
            orderDetail.setImage(item.getImage());  // 图片名称
            orderDetail.setAmount(item.getAmount());  // 当前金额,单份金额
            // 累加金额,    参数(单份金额.乘以(份数).转成int值)
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());
        // 向订单表插入数据,一条数据,需要给他为空的字段设置值,让数据完整
        orders.setId(orderId);  // 订单号
        orders.setOrderTime(LocalDateTime.now());  // 下单时间
        orders.setCheckoutTime(LocalDateTime.now());  // 支付时间
        orders.setStatus(2); // 当前状态 2 代表 待配送
        orders.setAmount(new BigDecimal(amount.get()));  // 订单总金额
        orders.setUserId(userId);  // 用户ID
        orders.setNumber(String.valueOf(orderId));  // 订单号
        orders.setUserName(user.getName());  // 用户数据
        orders.setConsignee(addressBook.getConsignee());  // 收货人
        orders.setPhone(addressBook.getPhone());  // 手机号
        // 省市区拼接 + 详细地址
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
        + (addressBook.getCityName() == null ? "" :addressBook.getCityName())
        + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
        + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        this.save(orders);
        // 向订单明细表插入数据,多条数据
        orderDetailService.saveBatch(orderDetails);
        // 清空购物车数据
        shoppingCarts.remove(queryWrapper);
    }
}
